//
//  YCCommentViewController.m
//  LOLBox
//
//  Created by mac on 15-3-24.
//  Copyright (c) 2015年 Honey. All rights reserved.
//

#import "YCCommentViewController.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "YCCommentAccout.h"
#import "YCReplyCommentAccout.h"
#import "YCCommentTableViewCell.h"


#define kNewEst @"http://115.28.43.55/lol/index.php/UserSdk/commentList/entity_id/%@/entity_type/news/orderBy/new/page/%d"
#define kHotEst @"http://115.28.43.55/lol/index.php/UserSdk/commentList/entity_id/%@/entity_type/news/orderBy/hot/page/%d"

@interface YCCommentViewController ()<UITableViewDataSource,UITableViewDelegate,MJRefreshBaseViewDelegate>
{
    NSInteger _page;
    NSString *_Id;
    BOOL _isFirst;
    // 刷新
    MJRefreshFooterView *_footerView;
    MJRefreshHeaderView *_headerView;
    MJRefreshBaseView *_baseView;
    
    CGFloat _rowFloat;
    
    UIButton *rightBtn;
    UIButton *leftBtn;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation YCCommentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _page = 1;
        self.dataSource = [NSMutableArray array];
        self.navigationItem.titleView = [self createSegment];
        self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
        //左边按钮
        [self createBackBarBtnWithTarget:self WithAction:@selector(popTheView)];
        [self createRefreshBarBtn];
    }
    return self;
}

- (void)popTheView
{
    if (self.dataSource.count > 0)
    {
        NSLog(@"清数据");
        [self.dataSource removeAllObjects];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initTableView];
    [self createTextFile];
    
    [self initFooterView];
    [self initHeaderView];
}

- (void)senderId:(NSString *)Id
{
    _Id = Id;
    [self AFN:kNewEst];
}

- (void)AFN:(NSString *)strUrl
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[NSString stringWithFormat:strUrl,_Id,_page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",arr);
        [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            
            YCCommentAccout *comment = [[YCCommentAccout alloc] init];
            comment.content = obj[@"content"];
            comment.entityId = obj[@"entity_id"];
            comment.entityType = obj[@"entity_type"];
            comment.floor = obj[@"floor"];
            comment.goldFinish = obj[@"gold_finish"];
            comment.goodNum = obj[@"good_num"];
            comment.hidden = obj[@"hidden"];
            comment.icon = obj[@"icon"];
            comment.Id = obj[@"id"];
            comment.ip = obj[@"ip"];
            comment.postTime = obj[@"post_time"];
            comment.reciveFlag = obj[@"recive_flag"];
            
            comment.replyId = obj[@"reply_id"];
            comment.replyUid = obj[@"reply_uid"];
            comment.reportNum = obj[@"report_num"];
            comment.Uid = obj[@"uid"];
            
            if (![obj[@"username"] isKindOfClass:[NSNull class]])
            {
                comment.username = obj[@"username"];
            }
            else
            {
                comment.username = @"游客";
            }
            //NSInteger repId = [comment.replyId integerValue];
            
            
            //NSString *repUid = [comment.replyUid stringValue];
            if ([obj[@"reply_id"] isEqualToString:@"0"])
            {
                comment.replyComment = nil;
            }
            
            else
            {
                YCReplyCommentAccout *repCom = [[YCReplyCommentAccout alloc] init];
                comment.replyComment = repCom;
                repCom.content = obj[@"reply_comment"][@"content"];
                
                repCom.content = obj[@"reply_comment"][@"content"];
                repCom.entityId = obj[@"reply_comment"][@"entity_id"];
                repCom.entityType = obj[@"reply_comment"][@"entity_type"];
                repCom.floor = obj[@"reply_comment"][@"floor"];
                repCom.goldFinish = obj[@"reply_comment"][@"gold_finish"];
                repCom.goodNum = obj[@"reply_comment"][@"good_num"];
                repCom.hidden = obj[@"reply_comment"][@"hidden"];
//                repCom.icon = obj[@"reply_comment"][@"icon"];
                repCom.Id = obj[@"reply_comment"][@"id"];
                repCom.ip = obj[@"reply_comment"][@"ip"];
                repCom.postTime = obj[@"reply_comment"][@"post_time"];
                repCom.reciveFlag = obj[@"reply_comment"][@"recive_flag"];
                
                repCom.replyId = obj[@"reply_comment"][@"reply_id"];
                repCom.replyUid = obj[@"reply_comment"][@"reply_uid"];
                repCom.reportNum = obj[@"reply_comment"][@"report_num"];
                repCom.Uid = obj[@"reply_comment"][@"uid"];
                repCom.username = obj[@"reply_comment"][@"username"];
                
                if (![obj[@"reply_comment"][@"username"] isKindOfClass:[NSNull class]])
                {
                    repCom.username = obj[@"username"];
                }
                else
                {
                    repCom.username = @"游客";
                }
            }
            [self.dataSource addObject:comment];
        }];
        [self.tableView reloadData];
        
        if (_headerView == _baseView)
        {
            [_headerView endRefreshing];
        }
        if (_footerView == _baseView)
        {
            
            [_footerView endRefreshing];
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
    }];
}

- (void)initTableView
{
    //CGRect rect = [UIScreen mainScreen].bounds;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 ) style:UITableViewStylePlain];
    
    //self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 95;
    //self.tableView.sectionHeaderHeight = 300;
//    self.tableView.backgroundColor = [UIColor redColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    /**
     *  去掉多余的线
     */
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = v;
    
    // 注册Cell
    [self.tableView registerNib:[UINib nibWithNibName:@"YCCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.view addSubview:self.tableView];
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YCCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    //cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];

    if (self.dataSource.count > 0)
    {
        YCCommentAccout *accout = self.dataSource[indexPath.row];
        [cell fillCellWithModel:accout];
        _rowFloat = [cell getRowHeight];
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YCCommentAccout *accout = self.dataSource[indexPath.row];
    CGFloat conH = [self setRowHeight:accout.content];
    CGFloat repConH = 0;
    
    if (accout.replyComment != nil)
    {
        repConH = [self setRowHeight:accout.replyComment.content];
        return conH + repConH + 70;
    }
    else
    {
        return conH + 45;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//计算高度
- (CGFloat)setRowHeight:(NSString *)s
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    CGRect frame = [s boundingRectWithSize:CGSizeMake(245, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
    return CGRectGetHeight(frame) ;
}

- (void)createTextFile
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 40)];
    v.backgroundColor = [UIColor blueColor];
    [self.view bringSubviewToFront:v];
    [self.view addSubview:v];
}

//创建一个切换按钮
- (UIView *)createSegment
{
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 144, 30)];
    v.tag = 13;
    
    leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"segmentNorLeft"] forState:UIControlStateNormal];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"segmentNorRight"] forState:UIControlStateNormal];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"segmentPreeLeft"] forState:UIControlStateSelected];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"segmentPreeRight"] forState:UIControlStateSelected];
    leftBtn.selected = YES;
    
    [leftBtn setTitle:@"最新" forState:UIControlStateNormal];
    [rightBtn setTitle:@"热门" forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    rightBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    
    leftBtn.tag = 11;
    rightBtn.tag = 12;
    
    [leftBtn addTarget:self action:@selector(reloadCurrentTablewView:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn addTarget:self action:@selector(reloadCurrentTablewView:) forControlEvents:UIControlEventTouchUpInside];
    
    leftBtn.frame = CGRectMake(0, 0, 72, 30);
    rightBtn.frame = CGRectMake(72, 0, 72, 30);
    
    [v addSubview:leftBtn];
    [v addSubview:rightBtn];
    
//    UIImage *leftImg = [UIImage imageNamed:@"segmentNorLeft"];
//    UIImage *rightImg = [UIImage imageNamed:@"segmentNorRight"];
//    
//    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[leftImg,rightImg]];
//    seg.frame = CGRectMake(0, 0, 144 * 2, 60);
//    seg.selectedSegmentIndex = 0;
    
    
    return v;
}

- (void)reloadCurrentTablewView:(UIButton *)btn
{
    if (_dataSource.count > 0)
    {
        [_dataSource removeAllObjects];
    }
    _page = 1;
    leftBtn.selected = NO;
    rightBtn.selected = NO;
    if (btn.tag == 11)
    {
        btn.selected = YES;
        [self AFN:kNewEst];
    }
    else if (btn.tag == 12)
    {
        btn.selected = YES;
        [self AFN:kHotEst];
    }
    
}


#pragma mark - 刷新
- (void)dealloc
{
    [_headerView free];
    [_footerView free];
}

- (void)initHeaderView
{
    _headerView = [[MJRefreshHeaderView alloc] initWithScrollView:_tableView];
    _headerView.delegate = self;
}

- (void)initFooterView
{
    _footerView = [[MJRefreshFooterView alloc] initWithScrollView:_tableView];
    _footerView.delegate = self;
}

#pragma mark - MJRefreshBaseViewDelegate

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    _baseView = refreshView;
    
    if (_baseView == _headerView)
    {
        NSLog(@"刷新");
        
        if (_dataSource.count > 0)
        {
            NSLog(@"删除了");
            [_dataSource removeAllObjects];
        }
        _page = 1;
    }
    else
    {
        NSLog(@"加载更多");
        _page++;
    }
    
    //NSLog(@"see%d",_page);
    [self AFN:kNewEst];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
